package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.cost.domain.SubTree;
import com.ruoyi.system.domain.AccMode;
import com.ruoyi.system.service.IAccModeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 会计账套Controller
 *
 * @author ruoyi
 * @date 2024-08-16
 */
@RestController
@RequestMapping("/system/mode")
public class AccModeController extends BaseController {
    @Autowired
    private IAccModeService accModeService;

    /**
     * 查询会计账套列表
     */
    // @PreAuthorize("@ss.hasPermi('system:mode:list')")
    @GetMapping("/list")
    public TableDataInfo list(AccMode accMode) {
        startPage();
        List<AccMode> list = accModeService.selectAccModeList(accMode);
        return getDataTable(list);
    }

    /**
     * 导出会计账套列表
     */
    // @PreAuthorize("@ss.hasPermi('system:mode:export')")
    @Log(title = "会计账套", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, AccMode accMode) {
        List<AccMode> list = accModeService.selectAccModeList(accMode);
        ExcelUtil<AccMode> util = new ExcelUtil<AccMode>(AccMode.class);
        util.exportExcel(response, list, "会计账套数据");
    }

    /**
     * 获取会计账套详细信息
     */
    // @PreAuthorize("@ss.hasPermi('system:mode:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(accModeService.selectAccModeById(id));
    }

    //    // @PreAuthorize("@ss.hasPermi('system:mode:query')")
    @GetMapping("listModes")
    public AjaxResult listModes() {
        Long userId = SecurityUtils.getUserId();
        List<AccMode> accModes =  accModeService.listModes(userId);
        List<SubTree> subTrees = subTrees(accModes);
        return success(subTrees);
    }
    public List<SubTree> subTrees (List<AccMode> accModes){
        // 使用TreeMap来自动按year排序
        Map<String, Map<String, SubTree>> treeMap = new TreeMap<>(Collections.reverseOrder());

        // 遍历accModes列表，将数据组织成treeMap
        for (AccMode data : accModes) {
            String year = data.getAccModeYear();
            String name = data.getAccModeName();
            String id = data.getId();

            // 如果year对应的map不存在，则初始化一个新的LinkedHashMap
            treeMap.putIfAbsent(year, new LinkedHashMap<>());

            // 获取year对应的map
            Map<String, SubTree> yearMap = treeMap.get(year);

            // 创建name对应的子节点
            SubTree childNode = new SubTree();
            childNode.setValue(id);
            childNode.setLabel(name);
            // 末级节点不再有子节点，因此将children设置为null
            childNode.setChildren(null);

            // 将子节点添加到year对应的map中
            yearMap.put(name, childNode);
        }

        // 将treeMap转换为最终的SubTree列表
        List<SubTree> result = new ArrayList<>();

        // 遍历treeMap的entry集合
        for (Map.Entry<String, Map<String, SubTree>> entry : treeMap.entrySet()) {
            // 创建year对应的节点
            SubTree yearNode = new SubTree();
            yearNode.setValue(entry.getKey());
            yearNode.setLabel(entry.getKey());

            // 将yearMap中的所有子节点添加到yearNode的children中
            List<SubTree> children = new ArrayList<>(entry.getValue().values());
            yearNode.setChildren(children);

            // 将yearNode添加到结果列表中
            result.add(yearNode);
        }


        return result;
    }



    /**
     * 新增会计账套
     */
    // @PreAuthorize("@ss.hasPermi('system:mode:add')")
    @Log(title = "会计账套", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody AccMode accMode) {
        accMode.setId(UUID.randomUUID().toString());
        return toAjax(accModeService.insertAccMode(accMode));
    }

    /**
     * 修改会计账套
     */
    // @PreAuthorize("@ss.hasPermi('system:mode:edit')")
    @Log(title = "会计账套", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody AccMode accMode) {
        return toAjax(accModeService.updateAccMode(accMode));
    }

    /**
     * 删除会计账套
     */
    // @PreAuthorize("@ss.hasPermi('system:mode:remove')")
    @Log(title = "会计账套", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(accModeService.deleteAccModeByIds(ids));
    }
}
